/*
 Modulo para dar de alta a un usuario
 Creado por Carlos Pastelin Morales 
 29/12/2014
 */
package Vistas;

import Controlador.Conexion;
import Vistas.Interface;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;


public class AltaUsuario extends javax.swing.JFrame {
/*Inicializamos las variable a utilzar*/    
    Conexion con;
    ResultSet rs;

    public AltaUsuario() {
        initComponents();//C.P.M Iniciamos los componentes
    }
    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLNombre = new javax.swing.JLabel();
        jLApellidoP = new javax.swing.JLabel();
        jLApellidoM = new javax.swing.JLabel();
        jLUser = new javax.swing.JLabel();
        jLPass = new javax.swing.JLabel();
        jTnombre = new javax.swing.JTextField();
        jTapellidop = new javax.swing.JTextField();
        jTapellidom = new javax.swing.JTextField();
        jTuser = new javax.swing.JTextField();
        jLTipoUsu = new javax.swing.JLabel();
        jCnivel = new javax.swing.JComboBox();
        jLPassAux = new javax.swing.JLabel();
        jTpass2 = new javax.swing.JPasswordField();
        jTpass = new javax.swing.JPasswordField();
        jBagregar = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenuItem2 = new javax.swing.JMenuItem();

        setTitle("Agregar usuario");
        setResizable(false);

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLNombre.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLNombre.setText("Nombre: ");
        jPanel1.add(jLNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(115, 40, -1, -1));

        jLApellidoP.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLApellidoP.setText("Apellido Paterno:");
        jPanel1.add(jLApellidoP, new org.netbeans.lib.awtextra.AbsoluteConstraints(56, 72, -1, -1));

        jLApellidoM.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLApellidoM.setText("Apellido Materno:");
        jPanel1.add(jLApellidoM, new org.netbeans.lib.awtextra.AbsoluteConstraints(54, 101, -1, -1));

        jLUser.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLUser.setText("Nombre de Usuario:");
        jPanel1.add(jLUser, new org.netbeans.lib.awtextra.AbsoluteConstraints(38, 133, -1, -1));

        jLPass.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLPass.setText("Contraseña:");
        jPanel1.add(jLPass, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 160, -1, 21));

        jTnombre.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jPanel1.add(jTnombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 38, 250, -1));

        jTapellidop.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jPanel1.add(jTapellidop, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 70, 250, -1));

        jTapellidom.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jPanel1.add(jTapellidom, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 99, 250, -1));

        jTuser.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jPanel1.add(jTuser, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 130, 252, -1));

        jLTipoUsu.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLTipoUsu.setText("Tipo de Usuario:");
        jPanel1.add(jLTipoUsu, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 220, 110, -1));

        jCnivel.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jCnivel.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Administrador", "Vendedor", "Capturista" }));
        jPanel1.add(jCnivel, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 220, 120, -1));

        jLPassAux.setFont(new java.awt.Font("Verdana", 1, 12)); // NOI18N
        jLPassAux.setText("Repetir Contraseña:");
        jPanel1.add(jLPassAux, new org.netbeans.lib.awtextra.AbsoluteConstraints(38, 189, -1, -1));

        jTpass2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jPanel1.add(jTpass2, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 190, 250, -1));

        jTpass.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jPanel1.add(jTpass, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 160, 250, -1));

        jBagregar.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jBagregar.setText("Agregar");
        jBagregar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBagregarActionPerformed(evt);
            }
        });
        jPanel1.add(jBagregar, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 260, 170, 36));

        jMenu1.setText("Archivo");

        jMenuItem1.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_C, java.awt.event.InputEvent.ALT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        jMenuItem1.setText("Cancelar");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Info");

        jMenuItem2.setText("Acerca de...");
        jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem2ActionPerformed(evt);
            }
        });
        jMenu2.add(jMenuItem2);

        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 503, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 321, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jBagregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBagregarActionPerformed
    /*Validamos que los componentes esten llenos*/
    if (jTnombre.getText().equals("") || jTapellidop.getText().equals("") || jTapellidom.getText().equals("")
            || jTuser.getText().equals("") || jTpass.getText().equals("") || jTpass2.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "No puede dejar espacios sin llenar");//C.P.M si falta alguno notificamos a el usuario 
    } else {//C.P.M de lo contrario obtenemos todos los datos y los enviamos 
        String aux = "";
        String nom = jTnombre.getText();
        String ap = jTapellidop.getText();
        String am = jTapellidom.getText();
        String user = jTuser.getText();
        String pass1 = jTpass.getText();
        String pass2 = jTpass2.getText();
        int nivel = jCnivel.getSelectedIndex();

        if (!pass1.equals(pass2)) {//C.P.M validamos que la contraseña coincida
            JOptionPane.showMessageDialog(null, "Las contraseñas no coinciden");//C.P.M si no es asi la contraseña no concide
            jTpass.setText("");//C.P.M limpamos los campos de pass
            jTpass2.setText("");//C.P.M limpamos los campos de pass
        } else {//C.P.M de lo contrario todo esta bien 
            try {
                // se hace la conexion con la base de datos
                con = new Conexion();
                String sql = "INSERT INTO `usuarios`(`nombre`, `apellido_paterno`, `apellido_materno`, `user`, `password`, `nivel`) VALUES ('" + nom + "','" + ap + "','" + am + "','" + user + "','" + pass1 + "','" + nivel + "')";
                con.ejecutar(sql);
                if (nivel == 0) {
                    aux = "Administrador(a)";
                }
                if (nivel == 1) {
                    aux = "Vendedor(a)";
                }
                if (nivel == 2) {
                    aux = "Capturista";
                }
                JOptionPane.showMessageDialog(null, "Usuario: [ " + user + " ] agregado como " + aux + " ");
                // se compara que el usuario de la base de datos es el mismo que el insertado
                //se comparan ambas contraseñas encriptadas
                jTnombre.setText("");
                jTapellidop.setText("");
                jTapellidom.setText("");
                jTuser.setText("");
                jTpass.setText("");
                jTpass2.setText("");
                this.dispose();

            } catch (ClassNotFoundException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

    }
}//GEN-LAST:event_jBagregarActionPerformed

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        if(JOptionPane.showConfirmDialog(rootPane, "Estás seguro de cerrarla?","Cerrar aplicación",1)==0){      
            this.hide();
        }
}//GEN-LAST:event_jMenuItem1ActionPerformed

private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
     JOptionPane.showMessageDialog(rootPane, "Realizado por:\n Nombres");
}//GEN-LAST:event_jMenuItem2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
       /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(AltaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(AltaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(AltaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(AltaUsuario.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AltaUsuario().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBagregar;
    private javax.swing.JComboBox jCnivel;
    private javax.swing.JLabel jLApellidoM;
    private javax.swing.JLabel jLApellidoP;
    private javax.swing.JLabel jLNombre;
    private javax.swing.JLabel jLPass;
    private javax.swing.JLabel jLPassAux;
    private javax.swing.JLabel jLTipoUsu;
    private javax.swing.JLabel jLUser;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JMenuItem jMenuItem2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField jTapellidom;
    private javax.swing.JTextField jTapellidop;
    private javax.swing.JTextField jTnombre;
    private javax.swing.JPasswordField jTpass;
    private javax.swing.JPasswordField jTpass2;
    private javax.swing.JTextField jTuser;
    // End of variables declaration//GEN-END:variables
}
